package com.thingcom.chinamobile.service;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ctg.ag.sdk.biz.AepDeviceManagementClient;
import com.ctg.ag.sdk.biz.aep_device_management.*;
import com.ctg.ag.sdk.core.model.BaseApiRequest;
import com.ctg.ag.sdk.core.model.BaseApiResponse;
import com.thingcom.base.util.RRException;
import com.thingcom.chinamobile.dto.DeviceDto;
import com.thingcom.chinamobile.factory.ApiClientFactory;
import com.thingcom.chinamobile.handler.BaseAepClientWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;

/**
 * @ClassName DeviceManageServiceImpl
 * @Description 设备管理服务实现类
 *              同步阻塞发送请求
 * @Author zhou tao
 * @Date 2019/12/17 15:36
 * @Version 1.0
 **/
@Service
@Slf4j
public class DeviceManageServiceImpl implements DeviceManageService {

	@Override
	public JSONObject createDevice(DeviceDto deviceDto) {
		AepDeviceManagementClient client = (AepDeviceManagementClient)ApiClientFactory.getInstance(deviceDto.getAppKey());
		CreateDeviceRequest request = new CreateDeviceRequest();
		request.setParamMasterKey(deviceDto.getMasterKey());

		return new BaseAepClientWrapper() {
			@Override
			public BaseApiResponse handleRequest(BaseApiRequest request) throws Exception {
				return client.CreateDevice((CreateDeviceRequest) request);
			}
		}.excute(request, JSONUtil.parseObj(deviceDto));
	}

	@Override
	public void updateDevice(DeviceDto deviceDto) {
		AepDeviceManagementClient client = (AepDeviceManagementClient)ApiClientFactory.getInstance(deviceDto.getAppKey() + "AepDeviceManagementClient");
		UpdateDeviceRequest request = new UpdateDeviceRequest();
		request.setParamMasterKey(deviceDto.getMasterKey());
		request.setParamDeviceId(deviceDto.getDeviceId());

		JSONObject response = new BaseAepClientWrapper() {
			@Override
			public BaseApiResponse handleRequest(BaseApiRequest request) throws Exception {
				return client.UpdateDevice((UpdateDeviceRequest)request);
			}
		}.excute(request, JSONUtil.parseObj(deviceDto));

		if (response.getInt("code") != 0) {
			throw new RRException(response.getStr("msg"));
		}
	}

	@Override
	public void removeDevice(DeviceDto deviceDto) {
		AepDeviceManagementClient client = (AepDeviceManagementClient)ApiClientFactory.getInstance(deviceDto.getAppKey());
		DeleteDeviceRequest request = new DeleteDeviceRequest();
		request.setParamMasterKey(deviceDto.getMasterKey());
		request.setParamProductId(deviceDto.getProductId());
		request.setParamDeviceIds(deviceDto.getDeviceIds());

		JSONObject response = new BaseAepClientWrapper() {
			@Override
			public BaseApiResponse handleRequest(BaseApiRequest request) throws Exception {
				return client.DeleteDevice((DeleteDeviceRequest) request);
			}
		}.excute(request, null);

		if (response.getInt("code") != 0) {
			throw new RRException(response.getStr("msg"));
		}
	}
}
